import { getHttp,http } from './http';
import { user, chat } from './protobuf-loader';
import { getToken } from '../utils/auth';
import { fileMd5 } from '@/utils/md5';
import {
  doesObjectExist,
  uploadObject
} from '@/api/file'
/**
 * 发送验证码
 * @param {string} email 邮箱地址
 * @returns {Promise<boolean>} 是否发送成功
 */
export const sendVerificationCode = async (email) => {
    const request = new user.VerificationCodeRequest();
    request.setEmail(email);
    
    const responseData = await http.post('/user/send-code',
      request.serializeBinary());
    // 手动反序列化响应
    const response = user.VerificationCodeResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    return {
      success: response.getSuccess(),
      code_id: response.getCodeId()
    };
};

/**
 * 用户注册
 * @param {Object} userInfo 用户信息
 * @param {string} userInfo.email 邮箱
 * @param {string} userInfo.username 用户名
 * @param {string} userInfo.password 密码
 * @param {string} [userInfo.avatar] 头像URL
 * @param {string} userInfo.code 验证码
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const registerUser = async (userInfo) => {
    let path = userInfo.avatar;
    if (userInfo.avatar instanceof ArrayBuffer) {
       const id = await fileMd5(new Uint8Array(userInfo.avatar))
        // 查看文件是否存在
        const result = await doesObjectExist(id)
        if (result.exist) {
            path = result.path
        }else {
            // 上传文件
            path = await uploadObject(new Uint8Array(userInfo.avatar))
        }
    }
    console.log("avatar path : ",path);
    console.log("avatar : ",userInfo.avatar);
    const request = new user.RegisterRequest();
    request.setEmail(userInfo.email);
    request.setUsername(userInfo.username);
    request.setPassword(userInfo.password);
    // request.setUsedefaultavatar(userInfo.useDefaultAvatar || false);
    request.setCode(userInfo.code);
    request.setCodeId(userInfo.code_id);
    request.setAvatar(path);
    
    const responseData = await http.post('/user/register',
      request.serializeBinary());
    const response = user.RegisterResponse.deserializeBinary(responseData.data).toObject();
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.success){
        throw response.message;
    }
    return {
      success: response.success,
      message: response.message
    };
};

/**
 * 获取用户统计数据
 * @param versionid 请求的时候携带的数据版本号信息
 * @returns {stats,version}
 */
export const getUserStats = async (email, versionid) => {
    const token = getToken();
    if (!token) throw new Error('未登录');
    
    const request = new user.UserStatsRequest();
    request.setToken(token);
    request.setEmail(email);
    request.setVersion(versionid);
    const responseData = await http.post('/user/stats',request.serializeBinary());
    const response = user.UserStatsResponse.deserializeBinary(responseData.data);
    console.log("responseData.status:",responseData.status);
    console.log("success:",response.getSuccess());
    console.log("message:",response.getMessage());
    if (responseData.status !== 200){
        console.error('请求失败', responseData)
        throw "请求失败"
    }
    if (!response.getSuccess()){
        console.error('请求失败', response.toObject())
        throw response.getMessage();
    }
    let stats = {};
    if (response.getStats()) {
        stats = {
            email: response.getStats().getEmail(),
            avatar: response.getStats().getAvatar(),
            name: response.getStats().getName(),
            solvedCount: response.getStats().getSolvedCount(),
            totalProblems: response.getStats().getTotalProblems(),
            solvedProblems: response.getStats().getSolvedProblemsList(),
          }
    }
    return {
        stats: stats,
        version: response.getVersion()
    }
};

/**
 * 密码登录
 * @param {string} email 邮箱
 * @param {string} password 密码
 * @returns {Promise<{success: boolean, message: string, token?: string, stats?: Object}>}
 */
export const loginUser = async (email, password) => {

    const request = new user.LoginRequest();
    request.setEmail(email);
    request.setPassword(password);
    const responseData = await http.post('/user/login',
      request.serializeBinary());
    const response = user.LoginResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){

        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    console.log("response.getSuccess()",response.getSuccess());
    console.log("response.getMessage()",response.getMessage());
    console.log("response.getToken()",response.getToken());
    console.log("response.getStats()",response.getStats());
    return {
      success: response.getSuccess(),
      message: response.getMessage(),
      token: response.getToken(),
      version: response.getVersion(),
      stats: response.getStats() ? {
        email: response.getStats().getEmail(),
        avatar: response.getStats().getAvatar(),
        name: response.getStats().getName(),
        solvedCount: response.getStats().getSolvedCount(),
        totalProblems: response.getStats().getTotalProblems(),
        solvedProblems: response.getStats().getSolvedProblemsList(),
      } : null
    };

};

/**
 * 验证码登录
 * @param {string} email 邮箱
 * @param {string} code 验证码
 * @returns {Promise<{success: boolean, message: string, token?: string, stats?: Object}>}
 */
export const codeLoginUser = async (email, code, codeId) => {

    const request = new user.CodeLoginRequest();
    request.setEmail(email);
    request.setCode(code);
    request.setCodeId(codeId || '');
    const responseData = await http.post('/user/code-login',
      request.serializeBinary());
    const response = user.LoginResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    return {
      success: response.getSuccess(),
      message: response.getMessage(),
      token: response.getToken(),
      version: response.getVersion(),
      stats: response.getStats() ? {
        email: response.getStats().getEmail(),
        avatar: response.getStats().getAvatar(),
        name: response.getStats().getName(),
        solvedCount: response.getStats().getSolvedCount(),
        totalProblems: response.getStats().getTotalProblems(),
        solvedProblems: response.getStats().getSolvedProblemsList(),
      } : null
    };

};


export const getProfileData = async (email) => {

        const token = getToken();
        if (!token) return new user.UserStatsSummaryResponse();
        
        const request = new user.UserStatsSummaryRequest();
        request.setToken(token);
        request.setEmail(email);
        const responseData = await http.post('/user/profile', 
            request.serializeBinary());
        const response = user.UserStatsSummaryResponse.deserializeBinary(responseData.data);
        if (responseData.status !== 200){
            console.error('请求失败', responseData)
            throw "请求失败"
        }
        if (!response.getSuccess()){
            console.error('请求失败', response)
            throw response.getMessage();
        }
        return {
          prodata: {
              solved: response.getStats().getSolvedProblems(),
              attempting: response.getStats().getAttemptingProblems(),
              published: response.getStats().getPublishedBlogs(),
              drafts: response.getStats().getDraftBlogs(),
              following: response.getStats().getFollowing(),
              followers: response.getStats().getFollowers(),
              mutual: response.getStats().getMutualFriends(),
              blog_likes_number: response.getStats().getBlogLikesNumber()
            }
        }

}
// /**
//  * 获取用户题目列表(统一处理已通过和尝试中题目)
//  * @param {string} userId 用户ID 
//  * @param {string} type 题目类型 (solved/attempting)
//  * @param {number} page 页码
//  * @param {number} pageSize 每页数量
//  * @returns {Promise<{problems: Array, total: number, page: number, pageSize: number, totalPages: number}>}
//  */
// export const getUserProblems = async (email, type = true, page = 1, pageSize = 10) => {
//   try {
//     const token = getToken();
//     if (!token) throw new Error('未登录');
    
//     const request = new problem.UserProblemListRequest();
//     request.setToken(token);
//     request.setEmail(email);
//     request.setPage(page);
//     request.setPageSize(pageSize);
//     request.setSolved(type); // 0: solved, 1: attempting
    
//     const responseData = await getHttp().post('/user/problems', 
//       request.serializeBinary());
//     const response = problem.UserProblemListResponse.deserializeBinary(responseData.data);
    
//     return {
//       problems: response.getProblemsList(),
//       page,
//       pageSize
//     };
//   } catch (error) {
//     console.error('获取题目列表失败:', error);
//     return {
//       problems: [],
//       total: 0,
//       page,
//       pageSize,
//       totalPages: 0
//     };
//   }
// };

/**
 * 用户登出
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const logoutUser = async () => {

    // 空请求体，token通过HTTP头传递
    const request = new user.LogoutRequest();
    request.setToken(getToken());
    const responseData = await http.post('/user/logout', request.serializeBinary());
    const response = user.LogoutResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    return {
      success: response.getSuccess(),
      message: response.getMessage()
    };

};

/**
 * 更新用户名
 * @param {string} newUsername 新用户名
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const updateUsername = async (newUsername) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.UpdateUsernameRequest();
    request.setToken(token);
    request.setNewUsername(newUsername);

    const responseData = await http.post('/user/update-username', 
      request.serializeBinary());
    const response = user.UpdateUsernameResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    return {
      success: response.getSuccess(),
      message: response.getMessage()
    };

};

/**
 * 更新头像
 * @param {string|Uint8Array} avatarData 头像数据(base64或二进制)
 * @returns {Promise<{success: boolean, message: string, avatar?: string}>}
 */
export const updateAvatarApi = async (avatarData) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.UpdateAvatarRequest();
    request.setToken(token);
    request.setAvatar(avatarData);

    const responseData = await http.post('/user/update-avatar', 
      request.serializeBinary());
    const response = user.UpdateAvatarResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    return {
      success: response.getSuccess(),
      message: response.getMessage(),
      avatar: response.getAvatar()
    };

};

/**
 * 修改密码
 * @param {string} currentPassword 当前密码
 * @param {string} newPassword 新密码
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const changePassword = async (currentPassword, newPassword) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.ChangePasswordRequest();
    request.setToken(token);
    request.setCurrentPassword(currentPassword);
    request.setNewPassword(newPassword);

    const responseData = await http.post('/user/change-password', 
      request.serializeBinary());
    const response = user.ChangePasswordResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    return {
      success: response.getSuccess(),
      message: response.getMessage()
    };

};

/**
 * 通过邮箱验证码修改密码
 * @param {string} verificationCode 验证码
 * @param {string} newPassword 新密码
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const changePasswordByEmail = async (verificationCode, newPassword, codeId) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.ChangePasswordByEmailRequest();
    request.setToken(token);
    request.setCode(verificationCode);
    request.setCodeId(codeId || '');
    request.setNewPassword(newPassword);

    const responseData = await http.post('/user/change-password-by-email', 
      request.serializeBinary());
    const response = user.ChangePasswordResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()){
        throw response.getMessage();
    }
    
    return {
      success: response.getSuccess(),
      message: response.getMessage()
    };
};

export const getFollowStatus = async (email) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.GetFollowStatusRequest();
    request.setToken(token);
    request.setEmail(email);

    const responseData = await http.post('/user/get-follow-status', request.serializeBinary());
    const response = user.GetFollowStatusResponse.deserializeBinary(responseData.data);0
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (response.getSuccess() == false) {
        throw response.getMessage();
    }
    return {
        following: response.getFollowing(),
        followers: response.getFollowers()
    };
}

/**
 * 关注用户
 * @param {string} email 用户邮箱
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const follow = async (email) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.FollowRequest();
    request.setToken(token);
    request.setEmail(email);

    const responseData = await http.post('/user/follow', request.serializeBinary());
    const response = user.FollowResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage();
    }
    return {
        success: response.getSuccess(),
        message: response.getMessage()
    };
};

/**
 * 取消关注用户
 * @param {string} email 用户邮箱
 * @returns {Promise<{success: boolean, message: string}>}
 */
export const unfollow = async (email) => {

    const token = getToken();
    if (!token) throw new Error('未登录');

    const request = new user.UnfollowRequest();
    request.setToken(token);
    request.setEmail(email);

    const responseData = await http.post('/user/unfollow', request.serializeBinary());
    const response = user.UnfollowResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage();
    }
    return {
        success: response.getSuccess(),
        message: response.getMessage()
    };
};


export const getUserInfo = async (email) => {
    const token = getToken();
    if (!token) throw new Error('未登录');
    const request = new user.GetUserInfoRequest();
    request.setToken(token);
    request.setEmail(email);

    const responseData = await http.post('/user/get-user-info', request.serializeBinary());
    const response = user.GetUserInfoResponse.deserializeBinary(responseData.data);
    if (responseData.status !== 200){
      console.error('请求失败', responseData)
        throw "请求失败"
    }
    if (!response.getSuccess()) {
        throw response.getMessage();
    }
    return {
        email: response.getEmail(),
        avatar: response.getAvatar(),
        name: response.getName()
    };
}

export const getDefaultAvatars = async () => {
  const request = new user.GetDefaultAvatarRequest();

  const responseData = await http.post('/user/get-default-avatar', request.serializeBinary());
  const response = user.GetDefaultAvatarResponse.deserializeBinary(responseData.data);
  if (responseData.status !== 200){
    console.error('请求失败', responseData)
      throw "请求失败"
  }
  if (!response.getSuccess()) {
      throw response.getMessage();
  }
  let list = [];
  response.getAvatarsList().forEach(element => {
    list.push(element);
  });
  return list;
}

/**
 * 获取关注我的用户列表
 * @param {string} email 用户邮箱
 * @param {number} page 页码
 * @param {number} pageSize 每页大小
 * @returns {Promise<{users: Array, total: number}>}
 */
export const getFollowers = async (email, page = 1, pageSize = 10) => {
  const token = getToken();
  if (!token) throw new Error('未登录');

  const request = new chat.GetFollowersRequest();
  request.setToken(token);
  request.setEmail(email);
  request.setPage(page);
  request.setPageSize(pageSize);

  const responseData = await getHttp().post('/chat/get-followers', request.serializeBinary());
  const response = chat.UsersResponse.deserializeBinary(responseData.data);
  if (responseData.status !== 200) {
    throw "请求失败";
  }
  if (!response.getSuccess()) {
    throw response.getMessage();
  }

  // 获取用户详细信息
  const userIds = response.getUserIdsList();
  const users = await Promise.all(
    userIds.map(async (userId) => {
      try {
        return await getUserInfo(userId);
      } catch (error) {
        console.error(`获取用户信息失败: ${userId}`, error);
        return { email: userId, name: userId, avatar: '' };
      }
    })
  );

  return {
    users,
    total: response.getTotal()
  };
};

/**
 * 获取我关注的用户列表
 * @param {string} email 用户邮箱
 * @param {number} page 页码
 * @param {number} pageSize 每页大小
 * @returns {Promise<{users: Array, total: number}>}
 */
export const getFollowing = async (email, page = 1, pageSize = 10) => {
  const token = getToken();
  if (!token) throw new Error('未登录');

  const request = new chat.GetFollowingRequest();
  request.setToken(token);
  request.setEmail(email);
  request.setPage(page);
  request.setPageSize(pageSize);

  const responseData = await getHttp().post('/chat/get-following', request.serializeBinary());
  const response = chat.UsersResponse.deserializeBinary(responseData.data);
  if (responseData.status !== 200) {
    throw "请求失败";
  }
  if (!response.getSuccess()) {
    throw response.getMessage();
  }

  // 获取用户详细信息
  const userIds = response.getUserIdsList();
  const users = await Promise.all(
    userIds.map(async (userId) => {
      try {
        return await getUserInfo(userId);
      } catch (error) {
        console.error(`获取用户信息失败: ${userId}`, error);
        return { email: userId, name: userId, avatar: '' };
      }
    })
  );

  return {
    users,
    total: response.getTotal()
  };
};

/**
 * 获取互相关注的用户列表
 * @param {number} page 页码
 * @param {number} pageSize 每页大小
 * @returns {Promise<{users: Array, total: number}>}
 */
export const getMutualFollowers = async (page = 1, pageSize = 10) => {
  const token = getToken();
  if (!token) throw new Error('未登录');

  const request = new chat.GetMutualFollowersRequest();
  request.setToken(token);
  request.setPage(page);
  request.setPageSize(pageSize);

  const responseData = await http.post('/chat/get-mutual-followers', request.serializeBinary());
  const response = chat.UsersResponse.deserializeBinary(responseData.data);
  if (responseData.status !== 200) {
    throw "请求失败";
  }
  if (!response.getSuccess()) {
    throw response.getMessage();
  }

  // 获取用户详细信息
  const userIds = response.getUserIdsList();
  const users = await Promise.all(
    userIds.map(async (userId) => {
      try {
        return await getUserInfo(userId);
      } catch (error) {
        console.error(`获取用户信息失败: ${userId}`, error);
        return { email: userId, name: userId, avatar: '' };
      }
    })
  );

  return {
    users,
    total: response.getTotal()
  };
};